package com.ych.modules.common.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ych.SDK.alibaba.ossSDK.AliOssUtil;
import com.ych.modules.api.authorInfc.user.entity.ModifyUserPayPasswordEntity;
import com.ych.modules.base.dbEntity.TUserAccountAmountTransformLogEntity;
import com.ych.modules.base.dbEntity.TUserAccountEntity;
import com.ych.modules.base.dbEntity.TUserInfoEntity;
import com.ych.modules.base.service.ITUserAccountAmountTransformLogService;
import com.ych.modules.base.service.ITUserAccountService;
import com.ych.modules.base.service.ITUserInfoService;
import com.ych.modules.base.service.ITUserTokenService;
import com.ych.modules.common.entity.modify.ModifyUserPwdEntity;
import com.ych.modules.common.entity.query.QueryUserInfoEntity;
import com.ych.modules.common.service.UserInfoService;
import com.ych.utils.TLMap;
import com.ych.utils.UUID;
import com.ych.utils.beanToMap.BeanMapUtil;
import com.ych.utils.mysqlPageUtil.Query;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;


/**
 * Created with IntelliJ IDEA.
 * Author: Usopp.tsui
 * Date: 2020/12/31
 * Time: 14:30
 * Description:
 */
@Service("UserInfoService")
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private ITUserInfoService                      itUserInfoService;
    @Autowired
    private ITUserTokenService                     itUserTokenService;
    @Autowired
    private AliOssUtil                             aliOssUtil;
    @Autowired
    private ITUserAccountService                   itUserAccountService;
    @Autowired
    private ITUserAccountAmountTransformLogService itUserAccountAmountTransformLogService;

    @Override
    public Page<TUserInfoEntity> listUserInfo(QueryUserInfoEntity entity) {
        Wrapper<TUserInfoEntity> wrapper = new EntityWrapper<TUserInfoEntity>()
                .where("1=1")
                .eq(StringUtils.isNotBlank(entity.getStatus()), "status", entity.getStatus())
                .eq(StringUtils.isNotBlank(entity.getUserId()), "user_id", entity.getUserId())
                .eq(StringUtils.isNotBlank(entity.getUserName()), "user_name", entity.getUserName())
                .eq(StringUtils.isNotBlank(entity.getMobile()), "mobile", entity.getMobile())
                .eq(StringUtils.isNotBlank(entity.getInvitation()), "invitation", entity.getInvitation());
        Page<TUserInfoEntity> page = itUserInfoService.selectPage(new Query<TUserInfoEntity>(BeanMapUtil.toPageQuery(entity)).getPage(), wrapper);
        return page;
    }

    @Override
    public TUserInfoEntity getUserInfo(String userId) {
        return itUserInfoService.selectById(userId);
    }

    @Override
    public void modifyPwd(ModifyUserPwdEntity entity) {
        TUserInfoEntity userInfoEntity = itUserInfoService.selectById(TLMap.getUserId());
        if (null == userInfoEntity) {
            throw new RuntimeException("未找到用户，请联系管理员！");
        }
        //比较原密码
        if (!userInfoEntity.getPassword().equals(new Sha256Hash(entity.getOldPwd(), userInfoEntity.getSalt()).toHex())) {//新系统匹配方式
            throw new RuntimeException("原密码错误！");
        }
        //新密码加密
        String newPwd = new Sha256Hash(entity.getNewPwd(), userInfoEntity.getSalt()).toHex();
        TUserInfoEntity tempUserInfoEntity = new TUserInfoEntity();
        tempUserInfoEntity.setUserId(userInfoEntity.getUserId());
        tempUserInfoEntity.setPassword(newPwd);
        itUserInfoService.updateById(tempUserInfoEntity);
    }

    @Override
    public void resetPwd(String userId) {
        TUserInfoEntity userInfoEntity = itUserInfoService.selectById(userId);
        if (null == userInfoEntity) {
            throw new RuntimeException("未找到用户，请联系管理员！");
        }
        //新密码加密
        String newPwd = new Sha256Hash(userInfoEntity.getMobile(), userInfoEntity.getSalt()).toHex();
        TUserInfoEntity tempUserInfoEntity = new TUserInfoEntity();
        tempUserInfoEntity.setUserId(userInfoEntity.getUserId());
        tempUserInfoEntity.setPassword(newPwd);
        itUserInfoService.updateById(tempUserInfoEntity);
    }

    @Override
    public void logout(String userId) {
        itUserTokenService.logout(userId);
    }

    @Override
    public void cmsUpdate(TUserInfoEntity userInfoEntity) {
        String userId = userInfoEntity.getUserId();
        TUserInfoEntity tUserInfo = itUserInfoService.selectById(userId);
        if (null == tUserInfo) {
            throw new RuntimeException("查询不到此用户");
        }
        //后管只修改以下字段
        tUserInfo.setStatus(userInfoEntity.getStatus());
        tUserInfo.setRoleIdList(userInfoEntity.getRoleIdList());
        tUserInfo.setPassword(null);
        //修改用户并,绑定用户角色
        itUserInfoService.update(tUserInfo);
    }

    @Override
    public TUserInfoEntity queryByUserId(String userId) {
        return itUserInfoService.queryByUserId(userId);
    }

    @Override
    public void apiUpdate(TUserInfoEntity userInfoEntity) {
        userInfoEntity.setUserId(TLMap.getUserId());
        if (StringUtils.isNotBlank(userInfoEntity.getUserHeadUrl())) {
            //转化为相对路径
            userInfoEntity.setUserHeadUrl(aliOssUtil.getRelativePath(userInfoEntity.getUserHeadUrl()));
        }
        //修改用户头像/用户名
        itUserInfoService.updateById(userInfoEntity);
    }

    @Override
    public Page<TUserInfoEntity> listUserTeam(QueryUserInfoEntity entity) {
        Wrapper<TUserInfoEntity> wrapper = new EntityWrapper<TUserInfoEntity>()
                .where("status='0'")
                .eq("recommender_user_id", TLMap.getUserId())
                .orderBy("create_time desc");
        Page<TUserInfoEntity> page = itUserInfoService.selectPage(new Query<TUserInfoEntity>(BeanMapUtil.toPageQuery(entity)).getPage(), wrapper);
        for (TUserInfoEntity userEntity : page.getRecords()) {
            userEntity.setUserHeadUrl(aliOssUtil.getOssObjectDownAuthUrl(userEntity.getUserHeadUrl()));
            userEntity.setPassword(null);
            userEntity.setSalt(null);
        }
        return page;
    }

    @Override
    public void transformGoldCoinToBrokerage(String userId, BigDecimal amount) {
        TUserAccountEntity accountEntity = itUserAccountService.selectById(userId);
        if (null == accountEntity) {
            throw new RuntimeException("用户不存在");
        }
        if (amount.compareTo(BigDecimal.ZERO) == -1) {
            throw new RuntimeException("转化金额不能为负数");
        }
        if (amount.compareTo(accountEntity.getGoldCoinAmount()) == 1) {
            throw new RuntimeException("金币余额不足");
        }
        TUserAccountAmountTransformLogEntity transformLogEntity = new TUserAccountAmountTransformLogEntity();
        transformLogEntity.setId(UUID.randomUUID());
        transformLogEntity.setUserId(userId);
        transformLogEntity.setAmount(amount);
        transformLogEntity.setAmountTransformType("10016001");
        transformLogEntity.setCreateTime(new Date());
        itUserAccountAmountTransformLogService.insert(transformLogEntity);
        itUserAccountService.alterBrokerageAmount("10000001", "10001009", transformLogEntity.getUserId(), transformLogEntity.getId(), transformLogEntity.getAmount().divide(new BigDecimal("10")));
        itUserAccountService.alterGoldCoinAmount("10000002", "10001009", transformLogEntity.getUserId(), transformLogEntity.getId(), transformLogEntity.getAmount());
    }

    @Override
    public void addPayPassword(ModifyUserPayPasswordEntity entity) {
        TUserInfoEntity userInfoEntity = itUserInfoService.selectById(TLMap.getUserId());
        if (null == userInfoEntity) {
            throw new RuntimeException("用户不存在");
        }
        String password = new Sha256Hash(entity.getPassword(), userInfoEntity.getSalt()).toHex();
        if (!password.equals(userInfoEntity.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        String payPassword = new Sha256Hash(entity.getPayPassword(), userInfoEntity.getSalt()).toHex();
        userInfoEntity.setPayPassword(payPassword);
        itUserInfoService.updateById(userInfoEntity);
    }
}
